#!/bin/bash

################################################################################
# Tonys Director64 - 100% Native Stable Dashboard (v5.5)
# NO PYTHON = NO CRASHES
################################################################################

# 1. Environment Setup
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [[ "$SCRIPT_DIR" == *"/Contents/MacOS"* ]]; then
    RESOURCES_DIR="$SCRIPT_DIR/../Resources"
    # Use native AppleScript to find the parent folder of the .app bundle
    # This is more robust against translocation and moving the app
    APP_PARENT_DIR=$(osascript -e 'tell application "Finder" to get POSIX path of (container of (path to me) as alias)' 2>/dev/null | sed 's/\/$//')
    [ -z "$APP_PARENT_DIR" ] && APP_PARENT_DIR="$( cd "$SCRIPT_DIR/../../.." && pwd )"
else
    RESOURCES_DIR="$SCRIPT_DIR"
    APP_PARENT_DIR="$SCRIPT_DIR"
fi
cd "$RESOURCES_DIR"

# Debug Log
DEBUG_LOG="/tmp/director64_debug.log"
echo "--- Launch Debug $(date) ---" > "$DEBUG_LOG"
echo "SCRIPT_DIR: $SCRIPT_DIR" >> "$DEBUG_LOG"
echo "APP_PARENT_DIR: $APP_PARENT_DIR" >> "$DEBUG_LOG"

# Source Homebrew
if [ -f "/opt/homebrew/bin/brew" ]; then eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -f "/usr/local/bin/brew" ]; then eval "$(/usr/local/bin/brew shellenv)"
fi

export WINEPREFIX="$HOME/.wine"
DATA_DIR="$HOME/.director64_data"
GAME_DIR="$DATA_DIR/game"
mkdir -p "$GAME_DIR"

# 1.5 Robust Installer Logic
install_missing_components() {
    FIX_SCRIPT_PATH="/tmp/director64_installer.sh"
    cat << 'EOF' > "$FIX_SCRIPT_PATH"
#!/bin/bash
clear
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔧 Tonys Director64 - Official System Installer"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "This utility will install all missing components for you."
echo "Please keep this window open and provide your Mac password if asked."
echo ""

# 1. Homebrew
if ! command -v brew &> /dev/null; then
    echo "📦 [1/5] Installing Homebrew..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    [ -f "/opt/homebrew/bin/brew" ] && eval "$(/opt/homebrew/bin/brew shellenv)"
    [ -f "/usr/local/bin/brew" ] && eval "$(/usr/local/bin/brew shellenv)"
else
    echo "✅ [1/5] Homebrew is already installed."
fi

# 2. Update & Install Core
echo "📦 [2/5] Updating Homebrew..."
brew update

echo "📦 [3/5] Installing Wine & FFmpeg..."
# Switch to wine-crossover as wine-stable is deprecated
brew tap gcenx/wine
brew install --cask gcenx/wine/wine-crossover
brew install ffmpeg winetricks

# 3. QuickTime
echo "📦 [4/5] Installing QuickTime 7.2 (Required for Video)..."
export WINEPREFIX="$HOME/.wine"
winetricks -q quicktime72

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ ALL COMPONENTS INSTALLED!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "You can now close this window and restart Tonys Director64."
echo ""
read -p "Press Enter to exit..."
exit
EOF
    chmod +x "$FIX_SCRIPT_PATH"
    open -a Terminal "$FIX_SCRIPT_PATH"
}

# 2. Licensing Logic
get_hwid() { ioreg -d2 -c IOPlatformExpertDevice | awk -F\" '/IOPlatformUUID/{print $(NF-1)}'; }
activate_license() {
    while true; do
        SERIAL_INPUT=$(osascript -e 'display dialog "Please enter your Serial Number to activate:" default answer "" with title "Director64 Verification" buttons {"Quit", "Activate"} default button "Activate" with icon note' 2>/dev/null)
        if echo "$SERIAL_INPUT" | grep -q "Quit"; then exit 0; fi
        SERIAL=$(echo "$SERIAL_INPUT" | sed -n 's/.*text returned:\([^,]*\).*/\1/p' | xargs)
        HWID=$(get_hwid)
        RESPONSE=$(curl -s -k -L -X POST -d "serial_key=$SERIAL&hwid=$HWID" "https://www.director64.com/activate_license.php")
        if [ "$(echo "$RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin).get('success', False))" 2>/dev/null)" == "True" ]; then
            echo "$RESPONSE" > "$DATA_DIR/license.json"; break
        else
            MSG=$(echo "$RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin).get('message', 'Unknown Error'))" 2>/dev/null)
            osascript -e "display dialog \"Activation Failed:\n$MSG\" buttons {\"Try Again\", \"Quit\"} with icon stop"
        fi
    done
}
[ ! -f "$DATA_DIR/license.json" ] && activate_license

# 3. Main Logic (Native Dashboard)
SIGNAL_FILE="/tmp/director_launch_signal"
rm -f "$SIGNAL_FILE"

# Detect App Translocation (macOS Gatekeeper randomized mount points)
IS_TRANS_L=false
if [[ "$SCRIPT_DIR" == *"/AppTranslocation/"* ]]; then
    IS_TRANS_L=true
fi

# Track the scan directory (defaults to parent folder of the app)
SCAN_DIR="$APP_PARENT_DIR"

# Background Launch Processor
process_launch() {
    local TARGET="$1"
    PROJECTOR=$(find "$GAME_DIR" -iname "projector.exe" -type f 2>/dev/null | head -n 1)
    [ -z "$PROJECTOR" ] && PROJECTOR=$(find "$RESOURCES_DIR" -iname "projector.exe" -type f 2>/dev/null | head -n 1)
    PROJECTOR_DIR="$( cd "$( dirname "$PROJECTOR" )" && pwd )"
    PROJECTOR_NAME="$( basename "$PROJECTOR" )"
    cd "$PROJECTOR_DIR"

    if [[ "$TARGET" == "LAUNCH_DEFAULT" ]]; then
        osascript -e "display notification \"Launching Director...\" with title \"Tonys Director64\""
        wine "$PROJECTOR_NAME" &>/dev/null &
    else
        LINK="$PROJECTOR_DIR/launch.dcr"
        cp "$TARGET" "$LINK" 2>/dev/null
        
        # Copy video assets so Projector can find them locally
        for ext in mp4 mov avi qt mpg mpeg m4v wmv swf; do
            find "$(dirname "$TARGET")" -maxdepth 1 -iname "*.$ext" -exec cp -n {} "$PROJECTOR_DIR/" \; 2>/dev/null
        done
        
        pkill -9 wine 2>/dev/null ; sleep 1
        osascript -e "display notification \"Launching: $(basename "$TARGET")\" with title \"Tonys Director64\""
        
        # Run Wine in a subshell and clean up assets ONLY after it exits
        (
            wine "$PROJECTOR_NAME" "launch.dcr" &>/dev/null
            
            # CRITICAL: Clean up to prevent .app bundle bloat
            rm -f "$LINK"
            for ext in mp4 mov avi qt mpg mpeg m4v wmv swf; do
                find "$PROJECTOR_DIR" -maxdepth 1 -iname "*.$ext" -delete 2>/dev/null
            done
        ) &
    fi
}

(
    while true; do
        if [ -f "$SIGNAL_FILE" ]; then
            path=$(cat "$SIGNAL_FILE")
            rm -f "$SIGNAL_FILE"
            process_launch "$path"
        fi
        sleep 1
    done
) &
SIGNAL_WATCHER_PID=$!

# ── Performance Optimization ──────────────────────────────────────────────────
# 1. "Warm Up" Wine Engine in the background
( wineserver -p & ) 2>/dev/null

# 2. Cache System Checks (Runs Once per session)
HB_ST="❌" ; [ -x "$(command -v brew)" ] && HB_ST="✅"
WINE_ST="❌" ; [ -x "$(command -v wine)" ] && WINE_ST="✅"
WT_ST="❌" ; [ -x "$(command -v winetricks)" ] && WT_ST="✅"
FF_ST="❌" ; [ -x "$(command -v ffmpeg)" ] && FF_ST="✅"

QT_ST="❌"
WINE_C="$WINEPREFIX/drive_c"
SEARCH_PATHS=( 
    "$WINE_C/windows/system32/qtmlClient.dll" 
    "$WINE_C/windows/syswow64/qtmlClient.dll" 
    "$WINE_C/windows/system32/QuickTime"
    "$WINE_C/Program Files/QuickTime"
    "$WINE_C/Program Files (x86)/QuickTime"
)
for p in "${SEARCH_PATHS[@]}"; do [ -e "$p" ] && QT_ST="✅" && break; done

ANY_MISSING=false
if [[ "$HB_ST" == "❌" || "$WINE_ST" == "❌" || "$WT_ST" == "❌" || "$FF_ST" == "❌" || "$QT_ST" == "❌" ]]; then ANY_MISSING=true; fi
# ──────────────────────────────────────────────────────────────────────────────

while true; do
    # 0. Check for DCRs
    FILES_FOUND=$(find "$SCAN_DIR" -maxdepth 1 -iname "*.dcr" -type f 2>/dev/null | wc -l | tr -d ' ')

    # Use Optimized Cached Status
    STATUS_TXT="Homebrew: $HB_ST | Wine: $WINE_ST | Winetricks: $WT_ST | FFmpeg: $FF_ST | QuickTime: $QT_ST"
    PROMPT_TXT="Tonys Director64 v5.5\n\n$STATUS_TXT\n\nFOLDER: $SCAN_DIR\n\nSELECT ACTION OR FILE:"

    # 3. Build Selection List
    TMPF=$(mktemp /tmp/dcr_list_XXXX.txt)
    find "$SCAN_DIR" -maxdepth 1 -iname "*.dcr" -type f | sort > "$TMPF"
    
    # Start with standard utilities
    AS_LIST="\"[ Launch Director Only ]\", \"─── UTILITIES ───\""
    
    # Add Install Missing at the TOP if something is gone
    if [ "$ANY_MISSING" = true ]; then
        AS_LIST="$AS_LIST, \"[ ⚠️ INSTALL MISSING COMPONENTS ]\""
    fi

    AS_LIST="$AS_LIST, \"[ 📁 Select Another Folder... ]\", \"[ Refresh List ]\", \"[ Tools: Video Converter ]\", \"[ Tools: Uninstall ]\", \"─── Director (DCR) Files ───\""
    
    LABELS=(); PATHS=()
    while IFS= read -r fpath; do
        fn=$(basename "$fpath")
        bytes=$(stat -f%z "$fpath" 2>/dev/null || echo 0)
        size=$(echo "scale=1; $bytes/1048576" | bc 2>/dev/null || echo 0)
        label="◈ $fn ($size MB)"
        LABELS+=("$label"); PATHS+=("$fpath")
        AS_LIST="$AS_LIST, \"$label\""
    done < "$TMPF" ; rm -f "$TMPF"

    PICKED=$(osascript <<APPLESCRIPT
    set theList to { $AS_LIST }
    set picked to choose from list theList \
        with title "Tonys Director64 Dashboard" \
        with prompt "$PROMPT_TXT" \
        OK button name "Select" \
        cancel button name "Quit"
    if picked is false then return "[ Quit Application ]"
    return item 1 of picked
APPLESCRIPT
    )

    # 4. Process Choice
    if [[ "$PICKED" == "[ Quit Application ]" ]]; then
        kill -9 $SIGNAL_WATCHER_PID 2>/dev/null
        exit 0
    fi
    if [[ "$PICKED" == "[ Refresh List ]" || "$PICKED" == "───"* ]]; then continue; fi

    if [[ "$PICKED" == "[ 📁 Select Another Folder... ]" ]]; then
        PICKED_FOLDER=$(osascript -e "try
            return POSIX path of (choose folder with prompt \"Select a folder containing DCR files:\")
        on error
            return \"\"
        end try" 2>/dev/null)
        if [ -n "$PICKED_FOLDER" ]; then SCAN_DIR="$PICKED_FOLDER"; fi
        continue
    fi

    if [[ "$PICKED" == "[ ⚠️ INSTALL MISSING COMPONENTS ]" ]]; then
        install_missing_components
        exit 0
    fi

    if [[ "$PICKED" == "[ Tools: Video Converter ]" ]]; then
        open -a Terminal "$RESOURCES_DIR/Video_Converter.sh" ; exit 0
    elif [[ "$PICKED" == "[ Tools: Uninstall ]" ]]; then
        open -a Terminal "$RESOURCES_DIR/uninstall_everything.sh" ; exit 0
    fi

    # Trigger Launch
    if [[ "$PICKED" == "[ Launch Director Only ]" ]]; then
        process_launch "LAUNCH_DEFAULT"
        kill -9 $SIGNAL_WATCHER_PID 2>/dev/null
        exit 0
    else
        SELECTED_PATH=""
        for i in "${!LABELS[@]}"; do
            if [ "${LABELS[$i]}" = "$PICKED" ]; then SELECTED_PATH="${PATHS[$i]}"; break; fi
        done
        if [ -n "$SELECTED_PATH" ]; then
            process_launch "$SELECTED_PATH"
            kill -9 $SIGNAL_WATCHER_PID 2>/dev/null
            exit 0
        fi
    fi
    
    continue
done

